// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "mainwindow.h"
#include "textedit.h"

#include <QAction>
#include <QApplication>
#include <QCompleter>
#include <QFile>
#include <QMenuBar>
#include <QMessageBox>
#include <QStringListModel>
#include <QFileDialog>
#include <QSettings>
#include <QFileInfo>
#include <QStyle>
#include <QToolBar>
#include <QTextStream>
//#include <QtAndroid>
//#include <QAndroidJniObject>

//! [0]
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), completer(nullptr), textEdit(new TextEdit)
{
    setCentralWidget(textEdit);
    createMenu();
    createToolBar();

    // 加载保存的最近文件列表
    QSettings settings("CustomCompleter", "TextEdit");
    recentFiles = settings.value("recentFiles").toStringList();
    // 初始化最近文件菜单
    createRecentFilesMenu();

    textEdit = new TextEdit;
    completer = new QCompleter(this);
    completer->setModel(modelFromFile(":/resources/wordlist.txt"));
    completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setWrapAround(false);
    textEdit->setCompleter(completer);

    setCentralWidget(textEdit);
    resize(500, 300);
    setWindowTitle(tr("Completer"));
}
//! [0]

//! [1]
void MainWindow::createMenu()
{
    QAction *exitAction = new QAction(tr("Exit"), this);
    QAction *aboutAct = new QAction(tr("About"), this);
    QAction *aboutQtAct = new QAction(tr("About Qt"), this);

    QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->setObjectName("fileMenu");

    openAction = new QAction(tr("&Open..."), this);
    openAction->setShortcuts(QKeySequence::Open);
    openAction->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton));
    connect(openAction, &QAction::triggered, this, &MainWindow::onOpen);
    fileMenu->addAction(openAction);

    saveAction = new QAction(tr("&Save"), this);
    saveAction->setShortcuts(QKeySequence::Save);
    saveAction->setIcon(style()->standardIcon(QStyle::SP_DialogSaveButton));
    connect(saveAction, &QAction::triggered, this, &MainWindow::onSave);
    fileMenu->addAction(saveAction);

    saveAsAction = new QAction(tr("Save &As..."), this);
    saveAsAction->setShortcuts(QKeySequence::SaveAs);
    connect(saveAsAction, &QAction::triggered, this, &MainWindow::onSaveAs);
    fileMenu->addAction(saveAsAction);

    fileMenu->addSeparator();

    closeAction = new QAction(tr("&Close"), this);
    closeAction->setShortcuts(QKeySequence::Close);
    closeAction->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton));
    connect(closeAction, &QAction::triggered, this, &MainWindow::onClose);
    fileMenu->addAction(closeAction);

    // 创建最近文件子菜单
    recentFilesMenu = fileMenu->addMenu(tr("Recent Files"));
    recentFilesMenu->setEnabled(false); // 初始禁用

    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

    QMenu *helpMenu = menuBar()->addMenu(tr("About"));
    helpMenu->addAction(aboutAct);
    helpMenu->addAction(aboutQtAct);
}
//! [1]

//! [2]
QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
        return new QStringListModel(completer);

#ifndef QT_NO_CURSOR
    QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif
    QStringList words;

    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        if (!line.isEmpty())
            words << QString::fromUtf8(line.trimmed());
    }

#ifndef QT_NO_CURSOR
    QGuiApplication::restoreOverrideCursor();
#endif
    return new QStringListModel(words, completer);
}
//! [2]

//! [3]
void MainWindow::about()
{
    QMessageBox::about(this, tr("About"), tr("This example demonstrates the "
        "different features of the QCompleter class."));
}
//! [3]

// 添加打开文件实现
bool MainWindow::openFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Error"),
            tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString()));
        return false;
    }

    QTextStream in(&file);

    in.setEncoding(QStringConverter::Utf8); // Qt 6编码设置方式
#ifndef QT_NO_CURSOR
    QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif
    textEdit->setPlainText(in.readAll());
#ifndef QT_NO_CURSOR
    QGuiApplication::restoreOverrideCursor();
#endif

    setWindowTitle(tr("%1 - Completer").arg(fileName));
    currentFile = fileName;
    updateRecentFiles();
    return true;
}

// 添加打开文件槽实现
void MainWindow::onOpen()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("Text Files (*.txt;*.ini);;All Files (*)"));
    if (!fileName.isEmpty())
        openFile(fileName);
}

void MainWindow::onSave()
{
    if (currentFile.isEmpty()) {
        onSaveAs();
    } else {
        saveFile(currentFile);
    }
}

void MainWindow::onSaveAs()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), QString(), tr("Text Files (*.txt);;All Files (*)"));
    if (!fileName.isEmpty())
        saveFile(fileName);
}

void MainWindow::onClose()
{
    textEdit->clear();
    currentFile.clear();
    setWindowTitle(tr("Text Edit"));
}


bool MainWindow::saveFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("Error"), 
                         tr("Cannot write file %1:\n%2.").arg(fileName).arg(file.errorString()));
    return false;
}

    QTextStream out(&file);
    out.setEncoding(QStringConverter::Utf8);
    out << textEdit->toPlainText();
    file.close();

    currentFile = fileName;
    setWindowTitle(tr("%1 - Text Edit").arg(currentFile));
    updateRecentFiles();
    return true;
}

void MainWindow::createRecentFilesMenu()
{
    // 清除现有菜单项
    if (recentFilesMenu) {
        recentFilesMenu->clear();
    } else {
        // 创建新的最近文件菜单（如果不存在）
        recentFilesMenu = new QMenu(tr("Recent Files"), this);
    }

    // 处理空列表情况
    if (recentFiles.isEmpty()) {
        QAction *noRecentAction = recentFilesMenu->addAction(tr("No recent files"));
        noRecentAction->setEnabled(false); // 禁用菜单项
    } else {
        // 添加最近文件列表
        QString f0 = "/storage/emulated/0/Fis/config.ini";
        /*recentFiles[0];
        QString path = f0.mid(0,f0.lastIndexOf("%2")+1);
        f0 = path + "config.ini";*/
        bool bExist = false;
        for (const QString &fileName : recentFiles) {
            if(fileName == f0){
                bExist = true;
            }

            QAction *action = new QAction(fileName, this);
            connect(action, &QAction::triggered, this, &MainWindow::onRecentFileTriggered);
            recentFilesMenu->addAction(action);
        }

        if(false == bExist){
            QAction *action = new QAction(f0, this);
            connect(action, &QAction::triggered, this, &MainWindow::onRecentFileTriggered);
            recentFilesMenu->addAction(action);
        }


        recentFilesMenu->setEnabled(true); // 禁用菜单项
    }

    QMenu *fileMenu = menuBar()->findChild<QMenu*>("fileMenu");
    if (fileMenu) {
        // 移除已存在的最近文件菜单（如果有）
        QList<QAction*> actions = fileMenu->actions();
        for (QAction *action : actions) {
            if (action->menu() == recentFilesMenu) {
                fileMenu->removeAction(action);
                break;
            }
        }
        fileMenu->addSeparator();
        fileMenu->addMenu(recentFilesMenu);
    }
}

void MainWindow::onRecentFileTriggered()
{
    QAction *action = qobject_cast<QAction*>(sender());
    if (action)
        openFile(action->text());
}

// 添加工具栏创建函数
// 添加工具栏创建和图标大小设置
void MainWindow::createToolBar()
{
    QToolBar *fileToolBar = addToolBar(tr("File Operations"));

    // 根据平台设置图标大小
#ifdef Q_OS_ANDROID
    // Android系统使用大图标
    QSize iconSize(48, 48); // 更大的图标尺寸
#else
    // 其他系统使用正常图标
    QSize iconSize(16, 16); // 默认尺寸
#endif

    fileToolBar->setIconSize(iconSize);

    // 添加文件操作按钮
    fileToolBar->addAction(openAction);
    fileToolBar->addAction(saveAction);
    fileToolBar->addAction(closeAction);

    // 添加分隔符
    fileToolBar->addSeparator();

    // 添加最近文件下拉菜单
    QAction *recentAction = new QAction(tr("Recent Files"), this);
    recentAction->setMenu(recentFilesMenu); // 关联到现有菜单
    fileToolBar->addAction(recentAction);

    // 允许工具栏停靠和移动
    fileToolBar->setAllowedAreas(Qt::TopToolBarArea | Qt::LeftToolBarArea);
    fileToolBar->setFloatable(true);
    fileToolBar->setMovable(true);
}

void MainWindow::updateRecentFiles()
{
    if (currentFile.isEmpty())
        return;

    // 移除已存在的文件条目（避免重复）
    recentFiles.removeAll(currentFile);
    // 将当前文件添加到列表开头
    recentFiles.prepend(currentFile);
    // 限制最近文件列表最多显示5个文件
    while (recentFiles.size() > 5)
        recentFiles.removeLast();

    // 保存最近文件列表到应用设置
    QSettings settings("CustomCompleter", "TextEdit");
    settings.setValue("recentFiles", recentFiles);

    // 更新最近文件菜单
    createRecentFilesMenu();
}
/*
// 添加权限请求函数
void MainWindow::requestStoragePermissions()
{
    QStringList permissions;
    permissions << "android.permission.READ_EXTERNAL_STORAGE"
                << "android.permission.WRITE_EXTERNAL_STORAGE";

    QtAndroid::requestPermissionsSync(permissions);
}

*/
